<template>
  <div ref="anchorsRef" class="v-anchors">
    <el-card>
      <el-timeline>
        <el-timeline-item v-for="(d, i) in anchorsList" :key="i" :type="activeIndex === i ? 'primary' : ''" hollow
          class="cursor-pointer" @click="handleClick(i)">
          <span :class="activeIndex === i && 'is--primary'">{{ d.innerText }}</span>
        </el-timeline-item>
      </el-timeline>
    </el-card>
    <div class="v-anchors-bths flex flex-col gap-2 mt-3 text-2xl">
      <svg-icon v-show="activeIndex === 0" icon-class="top" class=" text-white cursor-no-drop"></svg-icon>
      <svg-icon v-show="activeIndex !== 0" icon-class="top1" class=" text-white cursor-pointer"
        @click="handleClick(0)"></svg-icon>
      <svg-icon v-show="activeIndex === anchorsList.length - 1" icon-class="top" class=" text-white"
        style="transform: rotate(180deg);"></svg-icon>
      <svg-icon v-show="activeIndex !== anchorsList.length - 1" icon-class="top1"
        class=" text-white cursor-pointer" style="transform: rotate(180deg);"
        @click="handleClick(anchorsList.length - 1)"></svg-icon>
    </div>
  </div>
</template>

<script setup>
import { on, off } from '@/utils/dom'

const props = defineProps({
  classes: { type: String, default: '.v-title' },
})

const activeIndex = ref(0)
const anchorsList = ref([])
const { classes } = props

const anchorsRef = ref()
const pageEl = ref()
onMounted(() => {
  pageEl.value = document.querySelector('.v-page')
  on(pageEl.value, 'scroll', handleScroll)
  update()
})

onUnmounted(() => {
  off(pageEl.value, 'scroll', handleScroll)
  pageEl.value = null
})

const handleScroll = (e) => {
  const { scrollTop, offsetHeight, scrollHeight } = e.target
  activeIndex.value = anchorsList.value.findIndex((d) => d.getBoundingClientRect().y > 0)
  if (scrollTop + offsetHeight >= scrollHeight) {
    activeIndex.value = anchorsList.value.length - 1
  }
}

const handleClick = (i) => {
  anchorsList.value[i].scrollIntoView({ behavior: 'smooth' })
}

const update = () => {
  anchorsList.value = Array.from(pageEl.value.querySelectorAll(classes))
}

defineExpose({ update })
</script>

<style lang="scss">
  .v-anchors{
    .el-card__body{
      padding: 40px 20px 10px;
    }
    .el-timeline-item__node.is-hollow{
      background: var(--el-bg-color);
    }
  }
</style>